<template>
  <div id="bonusSettingDetailPage">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />

    <!-- 消息詳情卡片 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="基本參數" class="detail-card" :loading="loading">
        <template v-if="!loading && !bonusSetting.id">
          <a-empty description="數據加載失敗，請重試" />
        </template>
        <template v-else>
          <a-descriptions bordered>
            <a-descriptions-item label="獎金名稱">
              {{ bonusSetting.name }}
            </a-descriptions-item>
            <a-descriptions-item label="指定銷售產品Teams">
              <a-tag
                v-for="team in bonusSetting.productTeams"
                :key="team"
                color="blue"
              >
                {{ team }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="生效日期">
              {{ bonusSetting.validFrom }}
            </a-descriptions-item>
            <a-descriptions-item label="截止日期">
              {{ bonusSetting.validTo }}
            </a-descriptions-item>
            <a-descriptions-item label="狀態">
              <a-tag
                :bordered="false"
                color="processing"
                v-if="bonusSetting.status == 1"
                >啟用</a-tag
              >
              <a-tag :bordered="false" v-else>禁用</a-tag>
            </a-descriptions-item>

            <a-descriptions-item label="修改人">{{
              bonusSetting.updatedBy
            }}</a-descriptions-item>
            <a-descriptions-item label="更新時間">{{
              $formatDate(bonusSetting.updatedAt)
            }}</a-descriptions-item>
          </a-descriptions>
        </template>
      </a-card>
      <!-- 添加指標 -->
      <a-space>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <PlusOutlined />
          </template>
          添加獎金指標
        </a-button>
      </a-space>

      <a-table
        :dataSource="bonusSetting.bonusLevels"
        :columns="bonusLevelColumns"
        class="invoice-items-table"
        :loading="loading"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'targetAmount'">
            $ {{ record.targetAmount.toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'bonusAmount'">
            $ {{ record.bonusAmount.toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">修改</a-button>
            <a-button danger @click="handleDelete(record)">刪除</a-button>
          </template>
        </template>
      </a-table>

      <!-- 操作按鈕 -->
      <BackButton />
    </a-space>

    <!-- 新建模態框 -->
    <a-modal v-model:open="showModalCreate" title="添加獎金指標" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯獎金指標
        <a-tag color="warning">
          <ExclamationCircleOutlined /> ID: {{ editRecordId }}
        </a-tag>
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { bonusSettingApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import BackButton from "@/components/BackButton.vue";
import {
  tableColumns,
  getCreteFieldConfig,
  getEditFieldConfig,
} from "@/models/bonusLevel";
import { message, Modal } from "ant-design-vue";
import DynamicForm from "@/components/DynamicForm.vue";

const route = useRoute();
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});

// 麵包屑導航
const breadcrumbItems = [
  { url: "/bonus/setting", name: "獎金設置" },
  { url: "", name: "詳情" },
];

// 消息詳情數據
const bonusSetting = ref<any>({});
const loading = ref(true);
const bonusSettingId = Number(route.params.id);

// 獲取消息詳情
const fetchDetail = async () => {
  try {
    const { data } = await bonusSettingApi.getBonusSettingDetail(
      bonusSettingId
    );
    bonusSetting.value = data;
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    loading.value = false;
  }
};

// 初始化加載
onMounted(() => {
  fetchDetail();
});

const bonusLevelColumns = tableColumns;
const editFormData = reactive({});
// 新建
const showModalCreate = ref(false);
const handleCreate = async () => {
  showModalCreate.value = true;
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreteFieldConfig();
  }
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    await bonusSettingApi.createBonusLevel(bonusSettingId, data);
    message.success("創建獎金等級成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchDetail();
  } catch (error) {
    console.error("創建獎金等級失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const editRecordId = ref<number>(0);
const showModalEdit = ref(false);
const editFormRef = ref();
const handleEdit = async (record: any) => {
  showModalEdit.value = true;
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  Object.assign(editFormData, record);
};

const handleEditSubmit = async (data: any) => {
  try {
    await bonusSettingApi.updateBonusLevel(
      bonusSettingId,
      editRecordId.value,
      data
    );
    message.success("修改獎金等級成功");
    showModalEdit.value = false;
    fetchDetail();
  } catch (error) {
    console.error("修改獎金設置失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除獎金等級 ${record.name} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await bonusSettingApi.deleteBonusLevel(bonusSettingId, record.id);
        message.success("刪除獎金等級成功");
        fetchDetail();
      } catch (error) {
        console.error("刪除獎金等級失敗:", error);
      }
    },
  });
};
</script>

<style scoped></style>
